package by.koleda.photoupdater;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import by.koleda.photoupdater.manager.ContactsManager;
import by.koleda.photoupdater.model.Suggestion;

public class SuggestionsActivity extends Activity {
	
	private ListView mListView;
	private ArrayAdapter<Suggestion> mAdapter;
	private ArrayList<Suggestion> data = null;
	private ProgressDialog mDialog;
	
	public static final String SUBMIT_TAG = "submit";
	public static final String POINTS_TAG = "points";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.activity_suggestions);
		Intent intent = getIntent();
		int points = intent.getIntExtra(POINTS_TAG, 0);
		data = ContactsManager.getSuggestions(this, points);
		if (data.size() == 0) {
			Toast.makeText(this, R.string.suggestions_absent, Toast.LENGTH_LONG).show();
			finish();
		}
		mAdapter = new SuggestionsAdapter(this, data);
		mListView = (ListView) findViewById(R.id.listview_suggestions);
		mListView.setItemsCanFocus(false);
		mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		mListView.setAdapter(mAdapter);
	}
	
	public void onAcceptSuggestionsClick(View view) {

		if (data == null) {
			return;
		}
		showProgressDialog(R.string.loading_title, R.string.suggestions_accept, false);
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				ArrayList<Suggestion> submitted = new ArrayList<Suggestion>();

				for (Suggestion suggestion : data) {
					if (suggestion.isSelected()) {
						submitted.add(suggestion);
					}
				}

				int submit = ContactsManager.submitSuggestions(SuggestionsActivity.this, submitted);
				hideProgressDialog();
				Intent intent = new Intent();
				intent.putExtra(SUBMIT_TAG, submit);
				setResult(RESULT_OK, intent);
				finish();
			}
		}).start();
	}
	
	public void showProgressDialog(int title, int msg, boolean horizontal) {
		CharSequence message = getText(msg);
		mDialog = new ProgressDialog(this);
		mDialog.setTitle(title);
		mDialog.setMessage(message);
		mDialog.setIndeterminate(true);
	    mDialog.setCancelable(false);
	    if (horizontal) {
	    	mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	    }
	    mDialog.show();
	}
	
	public void hideProgressDialog() {
		mDialog.dismiss();
		
	}
}
